import useStores from '@/store';
import { intersection } from 'lodash';
import { observer } from 'mobx-react';
import { lazy, useEffect } from 'react';
import { Route, BrowserRouter as RouterDom, Routes } from 'react-router-dom';
import Notfound from '../pages/404';
import LazyComponent from './LazyImport';
import routers from './router';
import RouterTest from '../pages/routerTest';
function Router() {
  const { globalStore } = useStores();
  const { role } = globalStore;

  useEffect(() => {
    const handleError = event => {
      const error = event.reason; // 错误对象

      if (error.code === 401) {
        localStorage.removeItem('token');
        globalStore.showLoginModal = true;
      }

      event.preventDefault();
    };

    window.addEventListener('unhandledrejection', handleError);

    return () => {
      window.removeEventListener('unhandledrejection', handleError);
    };
  }, []);

  return (
    <RouterDom basename={'/'}>
      <Routes>
        {routers.map(item => {
          if (
            item.meat?.role &&
            item.meat?.role.length > 0 &&
            intersection(item.meat?.role, role).length === 0 &&
            process.env.NODE_ENV === 'production'
          ) {
            return null;
          }

          return (
            <Route
              path={item.path}
              key={item.path}
              element={<LazyComponent lazyChildren={lazy(() => import(`pages/${item.component}`))} route={item} />}
            >
              {item.children
                ? item.children.map(route => {
                    if (
                      route.meat?.role &&
                      route.meat?.role.length > 0 &&
                      intersection(route.meat?.role, role).length === 0 &&
                      process.env.NODE_ENV === 'production'
                    ) {
                      return null;
                    }

                    return (
                      <Route
                        path={route.path}
                        key={route.path}
                        element={
                          <LazyComponent
                            layout={item}
                            lazyChildren={lazy(() => import(`pages/${route.component}`))}
                            route={route}
                          />
                        }
                      />
                    );
                  })
                : null}
            </Route>
          );
        })}
        <Route path="/routerTest/*" element={<RouterTest />} />
        <Route path="*" element={<Notfound />}></Route>
      </Routes>
    </RouterDom>
  );
}

export default observer(Router);
